package com.love.cloud.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.cloud.admin.api.constants.NoticeMessageConstants;
import com.love.cloud.admin.api.entity.NoticeMessage;
import com.love.cloud.admin.api.vo.MessageHandleReadVo;
import com.love.cloud.admin.mapper.NoticeMessageMapper;
import com.love.cloud.admin.service.NoticeMessageService;
import com.love.cloud.common.core.constant.RedisJobConstant;
import com.love.cloud.common.core.exception.BusinessException;
import com.love.cloud.common.core.model.Job;
import com.love.cloud.common.core.util.RedisQueueUtils;
import com.love.cloud.common.core.util.RedisUtils;
import com.love.cloud.common.mybatis.util.PageUtils;
import com.love.cloud.common.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author hongdongqu
 */
@Service
public class NoticeMessageServiceImpl extends ServiceImpl<NoticeMessageMapper,NoticeMessage> implements NoticeMessageService {
    @Resource
    private PageUtils pageUtils;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RedisQueueUtils redisQueueUtils;


    @Override
    public Object getMessagePageByKey(String keyValue, String keyType) {
        if(StringUtils.isEmpty(keyValue)){
            throw new BusinessException("请传入关键字内容");
        }if(StringUtils.isEmpty(keyValue)){
            throw new BusinessException("请传入关键字类型");
        }
        Page page = pageUtils.page();
        QueryWrapper<NoticeMessage> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(NoticeMessageConstants.KEY_TYPE_MOBILE.equals(keyType),NoticeMessage::getMobile,keyValue)
                .eq(NoticeMessageConstants.KEY_TYPE_USER_ID.equals(keyType),NoticeMessage::getUserId,keyValue)
                .orderByDesc(NoticeMessage::getCreateTime);
        return this.page(page,queryWrapper);
    }

    @Override
    public Object saveMessage(String content, Long relationId, String relationType, Set<String> keyValues, String keyType) {
        if(keyValues==null&&keyValues.size()>0){
            throw new BusinessException("请传入关键字的内容");
        }if(StringUtils.isEmpty(keyType)){
            throw new BusinessException("请传入关键字的类型");
        }
        List<NoticeMessage> noticeMessageList=new ArrayList<>();
        for (String keyValue:keyValues) {
            NoticeMessage instructionMessage=new NoticeMessage();
            instructionMessage.setContent(content);
            if(NoticeMessageConstants.KEY_TYPE_MOBILE.equals(keyType)){
                instructionMessage.setMobile(keyValue);
            }else{
                instructionMessage.setUserId(Long.valueOf(keyValue));
            }

            instructionMessage.setRelationId(relationId);
            instructionMessage.setRelationType(relationType);
            noticeMessageList.add(instructionMessage);
            StringBuilder str=new StringBuilder();
            str.append("{").append(NoticeMessageConstants.KEY_TYPE_MOBILE.equals(keyType)?"\"mobile\":\"":"\"userId\":\"")
               .append(keyValue).append("\",\"content\":\"新的消息\"}");
            //发送websocket消息
            this.sendWebsocketMsg(str.toString(), RedisJobConstant.MESSAGE_CENTER);
        }
        this.saveBatch(noticeMessageList);
        return noticeMessageList;
    }

    @Override
    public Object handleRead(MessageHandleReadVo messageHandleReadVo) {
        String[] messageIds = messageHandleReadVo.getId().split(",");
        Long userId = SecurityUtils.getUser().getId();
        Set<String> needUpdateIds=new HashSet<>();
        for (String messageId:messageIds) {
            Object o = redisUtils.hget("MessageRead::" + userId, messageId);
            if(o==null){
                needUpdateIds.add(messageId);
                //添加redis中的信息
                redisUtils.hset("MessageRead::" + userId, messageId,"已读");
            }
        }
        if (needUpdateIds.size()>0) {
            NoticeMessage noticeMessage=new NoticeMessage();
            noticeMessage.setIsRead(true);
            QueryWrapper<NoticeMessage> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().in(NoticeMessage::getId,needUpdateIds);
            this.update(noticeMessage,queryWrapper);
        }
        return "阅读成功";
    }

    @Override
    public Object allHandleRead(MessageHandleReadVo messageHandleReadVo) {
        NoticeMessage noticeMessage=new NoticeMessage();
        noticeMessage.setIsRead(true);
        QueryWrapper<NoticeMessage> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(NoticeMessageConstants.KEY_TYPE_MOBILE.equals(messageHandleReadVo.getKeyType()),NoticeMessage::getMobile,messageHandleReadVo.getKeyValue())
                .eq(NoticeMessageConstants.KEY_TYPE_USER_ID.equals(messageHandleReadVo.getKeyType()),NoticeMessage::getUserId,messageHandleReadVo.getKeyValue());
        this.update(noticeMessage,queryWrapper);
        return "执行成功";
    }

    @Override
    public Object getUnReadNum(String keyValue, String keyType) {
        if(StringUtils.isEmpty(keyValue)){
            throw new BusinessException("请传入关键字内容");
        }if(StringUtils.isEmpty(keyValue)){
            throw new BusinessException("请传入关键字类型");
        }
        QueryWrapper<NoticeMessage> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(NoticeMessageConstants.KEY_TYPE_MOBILE.equals(keyType),NoticeMessage::getMobile,keyValue)
                .eq(NoticeMessageConstants.KEY_TYPE_USER_ID.equals(keyType),NoticeMessage::getUserId,keyValue)
                .eq(NoticeMessage::getIsRead,false);
        int count = this.count(queryWrapper);
        return count;
    }

    /**
     * 发送websocket消息
     * @param content
     * @param type
     */
    private void sendWebsocketMsg(String content, String type) {
        try{
            Job job=new Job();
            job.setTopic(type);
            job.setBody(content);
            redisQueueUtils.addJob(job,"http://sos-user-communication:10899");
        }catch (Exception ex){
            log.error("发送websocket失败:"+ex.getMessage());
        }
    }
}
